import React from "react";
import * as echarts from "echarts";
import "./index.scss";

const containerClass = "visbar-ecahrts-container";
interface IBaseEchartsProps {
  option: any;
  echartsInstance?: (echarts: echarts.ECharts) => void;
}
interface IBaseEchartsState {
  prevOption: any;      // 保存前一份option配置，再出错是进行回退
}
export default class BaseEcharts extends React.Component<IBaseEchartsProps, IBaseEchartsState> {
  wrapper = React.createRef();
  visbarEcharts: echarts.ECharts | null = null;
  constructor(props: IBaseEchartsProps) {
    super(props);
    this.state = {
      prevOption: null
    }
  }
  drawEcharts = (option: any, redraw?: boolean) => {
    try {
      this.visbarEcharts?.setOption(option, redraw);
      this.setState({ prevOption: option });
    } catch (err) {
      const { prevOption } = this.state;
      prevOption && this.visbarEcharts?.setOption(prevOption, redraw);
      !prevOption && ((this.wrapper.current as HTMLElement).innerHTML = `<div class="echarts-render-error">
        <h1>Echarts Render Error.</h1>
        <p>Echarts图表渲染错误，请检查是否存在必要配置项确实或有误!</p>
        <p>${(err as any)?.message}</p>
        <a href="https://echarts.apache.org/zh/option.html#title" target="_blank">Echarts配置请查阅</a>
      </div>`);
    }
  }
  componentDidMount() {
    if (this.wrapper.current) {
      const { option, echartsInstance } = this.props;
      this.visbarEcharts = echarts.init((this.wrapper.current as any));
      this.drawEcharts(option);
      echartsInstance && echartsInstance(this.visbarEcharts);
    }
  }
  shouldComponentUpdate(nextProps: IBaseEchartsProps) {
    if (nextProps.option !== this.props.option) {
      this.drawEcharts(nextProps.option, true);
    }
    return false;
  }
  
  render() {
    return <div className={containerClass} ref={(this.wrapper as any)}></div>
  }
}